package com.yaorange.certificate.service.impl;

import java.util.HashMap;
import java.util.List;

import com.yaorange.certificate.domain.NjtUnitConfig;
import com.yaorange.certificate.domain.NjtUserPerfect;
import com.yaorange.certificate.mapper.NjtUnitConfigMapper;
import com.yaorange.certificate.mapper.NjtUserPerfectMapper;
import com.yaorange.certificate.vo.NjtRegisterVo;
import com.yaorange.common.core.domain.AjaxResult;
import com.yaorange.common.core.domain.entity.SysUser;
import com.yaorange.common.enums.SysUserTypeEnum;
import com.yaorange.common.enums.UserStatus;
import com.yaorange.common.enums.YesOrNoEnum;
import com.yaorange.common.exception.ServiceException;
import com.yaorange.common.utils.DateUtils;
import com.yaorange.common.utils.SecurityUtils;
import com.yaorange.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.yaorange.certificate.mapper.NjtUserRegisterMapper;
import com.yaorange.certificate.domain.NjtUserRegister;
import com.yaorange.certificate.service.INjtUserRegisterService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户注册信息Service业务层处理
 *
 * @author coach tam
 * @date 2024-07-12
 */
@Service
public class NjtUserRegisterServiceImpl implements INjtUserRegisterService
{
    @Autowired
    private NjtUserRegisterMapper njtUserRegisterMapper;
    @Autowired
    private NjtUserPerfectMapper njtUserPerfectMapper;
    @Autowired
    private ISysUserService userService;

    @Value("${nongjt.default-role-id}")
    private Long defaultRoleId;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private NjtUnitConfigMapper njtUnitConfigMapper;


    /**
     * 查询用户注册信息
     *
     * @param id 用户注册信息主键
     * @return 用户注册信息
     */
    @Override
    public NjtUserRegister selectNjtUserRegisterById(Long id)
    {
        return njtUserRegisterMapper.selectNjtUserRegisterById(id);
    }

    /**
     * 查询用户注册信息列表
     *
     * @param njtUserRegister 用户注册信息
     * @return 用户注册信息
     */
    @Override
    public List<NjtUserRegister> selectNjtUserRegisterList(NjtUserRegister njtUserRegister)
    {
        return njtUserRegisterMapper.selectNjtUserRegisterList(njtUserRegister);
    }

    /**
     * 新增用户注册信息
     *
     * @param njtUserRegister 用户注册信息
     * @return 结果
     */
    @Override
    public int insertNjtUserRegister(NjtUserRegister njtUserRegister)
    {
        njtUserRegister.setCreateTime(DateUtils.getNowDate());
        return njtUserRegisterMapper.insertNjtUserRegister(njtUserRegister);
    }

    /**
     * 修改用户注册信息
     *
     * @param njtUserRegister 用户注册信息
     * @return 结果
     */
    @Override
    public int updateNjtUserRegister(NjtUserRegister njtUserRegister)
    {
        njtUserRegister.setUpdateTime(DateUtils.getNowDate());
        return njtUserRegisterMapper.updateNjtUserRegister(njtUserRegister);
    }

    /**
     * 批量删除用户注册信息
     *
     * @param ids 需要删除的用户注册信息主键
     * @return 结果
     */
    @Override
    public int deleteNjtUserRegisterByIds(Long[] ids)
    {
        return njtUserRegisterMapper.deleteNjtUserRegisterByIds(ids);
    }

    /**
     * 删除用户注册信息信息
     *
     * @param id 用户注册信息主键
     * @return 结果
     */
    @Override
    public int deleteNjtUserRegisterById(Long id)
    {
        return njtUserRegisterMapper.deleteNjtUserRegisterById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public NjtUserRegister findByMobilePhone(String mobilePhone) {
        NjtUserRegister njtUserRegister = new NjtUserRegister();
        njtUserRegister.setMobilePhone(mobilePhone);
        List<NjtUserRegister> list = njtUserRegisterMapper.selectNjtUserRegisterList(njtUserRegister);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(NjtRegisterVo njtRegisterVo) {
        //校验手机号是否已注册
        NjtUserRegister njtUserRegister = findByMobilePhone(njtRegisterVo.getMobilePhone());
        if (njtUserRegister != null) {
            throw new IllegalArgumentException("手机号已注册");
        }
        //1.新增系统用户表
        SysUser sysUser = new SysUser();

        sysUser.setUserType(SysUserTypeEnum.COMMON.CODE);
        //设置其他属性
        sysUser.setUserName(njtRegisterVo.getMobilePhone());
        //密码加密
        String encodePassword = passwordEncoder.encode(njtRegisterVo.getPassword());
        sysUser.setPassword(encodePassword);
        //设置默认角色
        sysUser.setRoleIds(new Long[]{defaultRoleId});
        userService.insertUser(sysUser);
        Long userId = sysUser.getUserId();
        //2.新增用户注册表（维护主键->系统用户主键）
        njtUserRegister = new NjtUserRegister();
        njtUserRegister.setId(userId);
        njtUserRegister.setMobilePhone(njtRegisterVo.getMobilePhone());
        njtUserRegister.setUserStatus(Integer.valueOf(UserStatus.OK.getCode()));
        njtUserRegister.setDelFlag(YesOrNoEnum.YES.CODE);
        njtUserRegister.setCreateTime(DateUtils.getNowDate());

        njtUserRegisterMapper.insertNjtUserRegister(njtUserRegister);
    }

    @Override
    @Transactional(readOnly = true)
    public AjaxResult getLoginUser() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        HashMap<String, Object> data = new HashMap<>(6);
        data.put("sysUser", SecurityUtils.getLoginUser());
        data.put("userPerfect", njtUserPerfectMapper.selectNjtUserPerfectById(userId));
        data.put("userRegister", njtUserRegisterMapper.selectNjtUserRegisterById(userId));
        return AjaxResult.success(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void perfect(NjtUserPerfect perfect) {
        NjtUnitConfig njtUnitConfig = new NjtUnitConfig();
        njtUnitConfig.setProvince(perfect.getProvince());
        njtUnitConfig.setCity(perfect.getCity());
        njtUnitConfig.setArea(perfect.getArea());
        List<NjtUnitConfig> unitConfigList = njtUnitConfigMapper.selectNjtUnitConfigList(njtUnitConfig);
        if (CollectionUtils.isEmpty(unitConfigList)) {
            throw new ServiceException("该地区暂无单位");
        }

        Long userId = SecurityUtils.getUserId();
        //1.新增完善信息表
        perfect.setId(userId);
        perfect.setCreateBy(SecurityUtils.getUsername());
        perfect.setCreateTime(DateUtils.getNowDate());
        //设置单位id(根据选中省市区获取单位id)
        perfect.setUnitId(unitConfigList.get(0).getId());
        perfect.setRegisterTime(SecurityUtils.getLoginUser().getUser().getCreateTime());
        perfect.setMobilePhone(SecurityUtils.getUsername());
        njtUserPerfectMapper.insertNjtUserPerfect(perfect);
        //2.更新用户注册表
        NjtUserRegister njtUserRegister = new NjtUserRegister();
        njtUserRegister.setId(userId);
        njtUserRegister.setPerfectFlag(YesOrNoEnum.YES.CODE);
        njtUserRegister.setPerfectTime(perfect.getCreateTime());
        njtUserRegisterMapper.updateNjtUserRegister(njtUserRegister);

    }
}
